pat甲級1013 參考柳神思路

1013 Battle Over Cities (25 分)

It is vitally important to have all the cities connected by highways in a war. If a city is occupied by the enemy, all the highways from/toward that city are closed. We must know immediately if we need to repair any other highways to keep the rest of the cities connected. Given the map of cities which have all the remaining highways marked, you are supposed to tell the number of highways need to be repaired, quickly.

For example, if we have 3 cities and 2 highways connecting city​1​​-city​2​​ and city​1​​-city​3​​. Then if city​1​​ is occupied by the enemy, we must have 1 highway repaired, that is the highway city​2​​-city​3​​.

Input Specification:

Each input file contains one test case. Each case starts with a line containing 3 numbers N (<1000), M and K, which are the total number of cities, the number of remaining highways, and the number of cities to be checked, respectively. Then M lines follow, each describes a highway by 2 integers, which are the numbers of the cities the highway connects. The cities are numbered from 1 to N. Finally there is a line containing K numbers, which represent the cities we concern.

Output Specification:

For each of the K cities, output in a line the number of highways need to be repaired if that city is lost.

Sample Input:

3 2 3
1 2
1 3
1 2 3

Sample Output:

1
0
0

       題目的大概意思就是說現在給我們一些個城市,城市數量用N來表示,然後再給我們一些連接這些城市的路,路的數量用M來表示,然後這些個城市正在打仗,某一個城市可能被敵方所佔領,當該城市被敵方佔領的時候它連接其他城市的道路也就會被摧毀,導致無法使用,而我們要做的就是要得到當某個城市被敵方所佔領後,爲了使我們的城市之間互相連通,我們一共需要修建多少條公路?

       大概思路就是求這個圖中把某一個城市除去後的連通分量(connected component),設該連通分量爲cc,則該題中所求的需要修建的道路的數量爲cc-1,因爲如果有5座城市,一共只需4條路就可完成對這五座城市的連接。對圖的存儲我採用的是鄰接矩陣,此處可能存在對內存的浪費,但最後還是成功通過,而遍歷的話我採用的是深度優先遍歷(DFS),採用廣度優先遍歷( BFS )應該也是可以的,在此就不贅述了。

#include<iostream>
#include<vector>
using namespace std;
void DFS(vector<bool> &visit, vector<vector<bool>> &E, int index)  //深度優先遍歷遞歸算法,index爲訪問的城市
{
	visit[index] = true;
	for (int i = 1; i < visit.size(); i++)
	{
		if (E[index][i] ==true && visit[i]==false)
		{
			DFS(visit, E, i);
		}
	}
}
int main()
{
	int N, M, K;
	cin >> N >> M >> K;
	vector<vector<bool>> E(N+1);   //邊 
	vector<bool> visit(N + 1);     //訪問標記
	vector<int> outPut(K);         //待求解城市數組
	for (int i = 0; i <= N; i++)
	{
		E[i].resize(N+1);
	}
	for (int i =0; i < M; i++)
	{
		int a, b;
		cin >> a >> b;
		E[a][b] = E[b][a] =true;
	}
	for (int i = 0; i < K; i++)    //對想要計算的城市進行記錄
	{
		int a;
		cin >> a;
		outPut[i] = a;
	}
	for (int i = 0; i < K; i++)
	{
		for (int v = 1; v < visit.size(); v++)
		{
			visit[v] = false;
		}
		int cnt=0;         //圖的連通分量
		visit[outPut[i]] = true;
		for (int j = 1; j <= N; j++)
		{
			if (!visit[j])            
			{
				DFS(visit, E, j);         //從一個點開始對一個連通分量進行遍歷
				cnt++;                    //連通分量數加一
			}
		}
		if (i < K - 1)
		{
			cout << cnt - 1 << endl;
		}
		else
		{
			cout << cnt-1;
		}
	}
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章